Telegram Group & Telegram Channel
🖥 Задача «Перехват исключений и потеря контекста» (C# 12)

Дан код:


using System;
using System.Runtime.ExceptionServices;

class Program
{
static void Main()
{
try
{
Console.WriteLine(Foo());
}
catch (Exception ex)
{
Console.WriteLine($"Catch: {ex.Message}");
}
}

static int Foo()
{
try
{
return Bar();
}
finally
{
throw new Exception("finally in Foo");
}
}

static int Bar()
{
try
{
throw new Exception("error in Bar");
}
finally
{
Console.WriteLine("Bar finally executed");
}
}
}


Вопросы:
• Что напечатает программа и почему?
• В каком порядке выполняются блоки try / finally?
• Какая из двух ошибок дойдёт до catch, а какая потеряется?
• Как изменить код, чтобы не терять информацию о первой ошибке?

Разбор:
• Bar бросает Exception("error in Bar"). Прежде чем исключение покинет метод, выполняется его finally, выводя Bar finally executed.
• Управление переходит в Foo. Там срабатывает finally, который бросает новое исключение ("finally in Foo").
• По правилам CLR новое исключение из finally заменяет текущее. Первая ошибка пропадает.
• В Main перехватывается только «finally in Foo».

Консольный вывод:

Bar finally executed
Catch: finally in Foo

Как сохранить обе ошибки

Обернуть второе исключение так, чтобы первая причина не потерялась, например:


finally
{
var pending = new Exception("finally in Foo");
throw new AggregateException("Foo failed", pending);
}


или переслать исходное исключение через ExceptionDispatchInfo:

Exception pending = null;

static int Foo()
{
try
{
return Bar();
}
catch (Exception ex)
{
pending = ex; // сохраняем первую причину
throw;
}
finally
{
if (pending != null)
ExceptionDispatchInfo.Capture(pending).Throw();
}
}```

Так ни одна ошибка не будет потеряна, а отладка станет нагляднее.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_1001_notes/710
Create:
Last Update:

🖥 Задача «Перехват исключений и потеря контекста» (C# 12)

Дан код:


using System;
using System.Runtime.ExceptionServices;

class Program
{
static void Main()
{
try
{
Console.WriteLine(Foo());
}
catch (Exception ex)
{
Console.WriteLine($"Catch: {ex.Message}");
}
}

static int Foo()
{
try
{
return Bar();
}
finally
{
throw new Exception("finally in Foo");
}
}

static int Bar()
{
try
{
throw new Exception("error in Bar");
}
finally
{
Console.WriteLine("Bar finally executed");
}
}
}


Вопросы:
• Что напечатает программа и почему?
• В каком порядке выполняются блоки try / finally?
• Какая из двух ошибок дойдёт до catch, а какая потеряется?
• Как изменить код, чтобы не терять информацию о первой ошибке?

Разбор:
• Bar бросает Exception("error in Bar"). Прежде чем исключение покинет метод, выполняется его finally, выводя Bar finally executed.
• Управление переходит в Foo. Там срабатывает finally, который бросает новое исключение ("finally in Foo").
• По правилам CLR новое исключение из finally заменяет текущее. Первая ошибка пропадает.
• В Main перехватывается только «finally in Foo».

Консольный вывод:

Bar finally executed
Catch: finally in Foo

Как сохранить обе ошибки

Обернуть второе исключение так, чтобы первая причина не потерялась, например:


finally
{
var pending = new Exception("finally in Foo");
throw new AggregateException("Foo failed", pending);
}


или переслать исходное исключение через ExceptionDispatchInfo:

Exception pending = null;

static int Foo()
{
try
{
return Bar();
}
catch (Exception ex)
{
pending = ex; // сохраняем первую причину
throw;
}
finally
{
if (pending != null)
ExceptionDispatchInfo.Capture(pending).Throw();
}
}```

Так ни одна ошибка не будет потеряна, а отладка станет нагляднее.

BY C# 1001 notes


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_1001_notes/710

View MORE
Open in Telegram


C 1001 notes Telegram | DID YOU KNOW?

Date: |

Look for Channels Online

You guessed it – the internet is your friend. A good place to start looking for Telegram channels is Reddit. This is one of the biggest sites on the internet, with millions of communities, including those from Telegram.Then, you can search one of the many dedicated websites for Telegram channel searching. One of them is telegram-group.com. This website has many categories and a really simple user interface. Another great site is telegram channels.me. It has even more channels than the previous one, and an even better user experience.These are just some of the many available websites. You can look them up online if you’re not satisfied with these two. All of these sites list only public channels. If you want to join a private channel, you’ll have to ask one of its members to invite you.

The seemingly negative pandemic effects and resource/product shortages are encouraging and allowing organizations to innovate and change.The news of cash-rich organizations getting ready for the post-Covid growth economy is a sign of more than capital spending plans. Cash provides a cushion for risk-taking and a tool for growth.

C 1001 notes from br


Telegram C# 1001 notes
FROM USA